from django.shortcuts import render
from testapp.models import Vendata, Apicat, Apidata, Apimethod, Casecat, Casedata, Commonmethod
# Create your views here.
from django.http import JsonResponse, HttpResponse, FileResponse, StreamingHttpResponse
from testapp.dataio.dataiofactory import DataIOFactory
from testapp.excute.runing import Runingfac
from testapp.control.ctmanage import CtManage

import json
from django.db.models import Q

fac = DataIOFactory()
manage = CtManage()

"""
配置环境相关接口------开始----------------------------------------------------------
"""
def get_env(request):
    """获取所有环境"""
    try:
        data = {}
        data['inputstr'] = request.GET.get('inputstr')
        data['pageSize'] = int(request.GET.get('pageSize'))
        data['currentPage'] = int(request.GET.get('currentPage'))
    except Exception as e:
        return JsonResponse({'code':0, 'msg':'获取环境信息失败，具体错误' + str(e)})
    isOK, result = manage.getEnv(data)
    if isOK:
        return JsonResponse({'code': 1, 'data': result})
    else:
        return JsonResponse({'code': 0, 'msg': '获取环境信息失败，具体错误' + str(result)})


def get_cenv(request):
    if request.method == 'GET':
        try:
            obj_envs = list(Vendata.objects.all().values())
            return JsonResponse({'code': 1, 'data': obj_envs})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '查询环境信息出现异常，具体错误:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})

def get_data_conf(request):
    if request.method == 'GET':
        env_id = request.GET.get('env_id')
        isOK, result = manage.get_data_conf(env_id)
        if isOK:
            return JsonResponse({'code': 1, 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': '获取数据库配置失败，具体原因：【{}】'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})

def query_env(request):
    """
         #查询环境：
    """
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        try:
            obj_env = Vendata.objects.filter(
                Q(id__icontains=data['inputstr']) | Q(name__icontains=data['inputstr']) | Q(url__icontains=data['inputstr']) |
                Q(db__icontains=data['inputstr']) | Q(dbuser__icontains=data['inputstr'])).values()
            env = list(obj_env)
            return JsonResponse({'code': 1, 'data': env})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '查询环境信息出现异常，具体错误:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})

def add_env(request):
    """#添加环境："""
    print(request.method)
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        isOK, result = manage.add_env(data)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '添加环境数正常'})
        else:
            return JsonResponse({'code': 0, 'msg': '添加环境数据异常，具体原因' + str(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})


def updata_env(request):
    """
    更新环境信息
    """
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        isOK, result = manage.updata_env(data)
        if isOK:
            return JsonResponse({"code": 1, "msg": "数据修改成功"})
        else:
            return JsonResponse({"code": 0, "msg": "数据修改失败，具体原因：[{}]".format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})

def delete_env(request):
    """
    删除环境
    """
    if request.method == 'POST':
        try:
            #删除环境
            data = json.loads(request.body.decode('utf-8'))
            obj_env = Vendata.objects.get(id=data['id'])
            obj_env.delete()
            return JsonResponse({"code": 1, "msg": "数据删除成功"})
        except Exception as e:
            if '1451' in str(e):
                return JsonResponse({"code": 0, "msg": "数据删除失败，具体原因：有执行计划使用了此环境" })
            else:
                return JsonResponse({"code": 0, "msg": "数据删除失败，具体原因：" + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})


def getenv_byid(request):
    """通过id获取数据"""
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            obj_env = Vendata.objects.filter(Q(id=data['id'])).values()
            envs = list(obj_env)
            return JsonResponse({"code": 1, "data": envs})
        except Exception as e:
            return JsonResponse({"code": 0, "msg": "此id获取数据失败，具体原因：" + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})
"""
配置环境相关接口------结束----------------------------------------------------------
"""





"""
接口管理树相关接口------开始----------------------------------------------------------
"""

def getApiCate(request):
    """
    获取API树
    """
    if request.method == 'GET':
        try:
            cat_type = int(request.GET.get('cat_type'))
            if cat_type == 1:   #1代表用例：
                obj_cats = Casecat.objects.all().values()
            elif cat_type == 0:   #0代表接口
                obj_cats = Apicat.objects.all().values()
            cat = fac.Catagery(list(obj_cats))
            return JsonResponse({'code': 1, 'data': cat})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '查询树数据失败,具体原因:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})




def addApinode(request):
    """
    添加节点
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            if data['cat_type'] == 1:   #1代表用例：
                obj_cat = Casecat(name=data['name'], parentid=data['parentid'], level=data['level'])
                obj_cat.save()
                cat = obj_cat.id
            elif data['cat_type'] == 0:   #0代表接口：
                obj_cat = Apicat(name=data['name'], parentid=data['parentid'], level=data['level'])
                obj_cat.save()
                cat = obj_cat.id
            return JsonResponse({'code': 1, 'msg': '添加成功', "data": cat})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '添加节点失败,具体原因:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})




def delApinode(request):
    """
    删除节点
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            if data['id'] == 1:
                return JsonResponse({'code': 0, 'msg': '删除节点失败,具体原因:根节点不可删除'})
            if data['cat_type'] == 1:
                obj_cat = Casecat.objects.filter(Q(parentid=data['id'])).values()
                obj_api = Casedata.objects.filter(Q(catid=data['id'])).values()
                if len(obj_cat) == 0 and len(obj_api) == 0:
                    obj_catA = Casecat.objects.get(id=data['id'])
                    obj_catA.delete()
                else:
                    return JsonResponse({'code': 0, 'msg': '删除失败，其下有子节点或接口'})
            elif data['cat_type'] == 0:
                obj_cat = Apicat.objects.filter(Q(parentid=data['id'])).values()
                obj_cas = Apidata.objects.filter(Q(catid=data['id'])).values()
                if len(obj_cat) == 0 and len(obj_cas) == 0:
                    obj_catA = Apicat.objects.get(id=data['id'])
                    obj_catA.delete()
                else:
                    return JsonResponse({'code': 0, 'msg': '删除失败，其下有子节点或接口'})
            return JsonResponse({'code': 1, 'msg': '删除成功'})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '删除节点失败,具体原因:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})


def updataCat(request):
    """
    更新树节点
    """
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        isOK, result = manage.updateCat(data)
        if isOK:
            return JsonResponse({'code': 1, 'msg': result})
        else:
            return JsonResponse({'code': 0, 'msg': '更新树节点失败，具体原因：{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})


"""
接口管理树相关接口------结束----------------------------------------------------------
"""




"""
接口管理相关接口------开始----------------------------------------------------------
"""
def getApidata(request):
    """
    获取接口数据
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            res = fac.queryApi(data)
            return JsonResponse({'code': 1, 'msg': '查询数据成功:', "data": res})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '查询数据失败,具体原因:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})



def addApidata(request):
    """
    添加接口
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            obj_api = Apidata(name=data['name'], catid_id=data['catid_id'], api=data['api'],
                              apimethod=data['apimethod'], headers=data['headers'], body=data['body'],
                              response=data['response'])
            obj_api.save()
            return JsonResponse({'code': 1, 'msg': '添加数据成功'})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '添加数据失败,具体原因:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})


def queryApidata(request):
    """
    条件查询
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            obj_api = Apidata.objects.filter(Q(id__icontains=data['inputstr']) | Q(name__icontains=data['inputstr']) | Q(
                    api__icontains=data['inputstr']) | Q(apimethod__icontains=data['inputstr'])).values()
            api = list(obj_api)
            return JsonResponse({'code': 1, 'data': api})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '查询数据失败,具体原因:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})


def delApidata(request):
    """
    删除接口
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            obj_api = Apidata.objects.get(id=data['id'])
            json_api = json.loads(str(obj_api))
            if json_api['MOCK']:
                return JsonResponse({'code': 0, 'msg': '接口Mocking,请先停止Mock'})
            obj_api.delete()
            return JsonResponse({'code': 1, 'msg': '删除接口成功'})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '删除接口失败,具体原因:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})


def updateApi(request):
    """
    更新接口
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            obj_api = Apidata.objects.get(id=data['id'])
            json_api = json.loads(str(obj_api))
            if json_api['MOCK']:
                return JsonResponse({'code': 0, 'msg': '接口Mocking,请先停止Mock'})
            obj_api.name = data['name']
            obj_api.api = data['api']
            obj_api.apimethod = data['apimethod']
            obj_api.headers = data['headers']
            obj_api.body = data['body']
            obj_api.response = data['response']
            obj_api.save()
            return JsonResponse({'code': 1, 'msg': '更新接口成功'})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '更新接口失败,具体原因:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})


def apiMock(request, path):
    """
    接口MOCK
    """

    # 获取本次请求的路径，不是数据库里存的路径
    route = list(Apidata.objects.filter(Q(api__icontains=path)).values())   #这里有一个BUG，包含与被包含的接口，被包含的那个MOCK将出问题
    if(len(route) == 0):
        return JsonResponse({'code': 0, 'msg': '接口文档还未录入接口'})
    if route[0]['ismock'] == 0:
        return JsonResponse({'code': 0, 'msg': '接口未MOCK，请先MOCK'})
    if route[0]['apimethod'] != request.method:
        return JsonResponse({'code': 0, 'msg': '接口请求类型与录入接口的类型不匹配，录入接口类型为[{}]'.format(route[0]['apimethod'])})
    # 参数判断有问题，后期满足各中格式的接口
    params = request.body.decode('utf-8')
    if route[0]['body'] != params:
        return JsonResponse({'code': 0, 'msg': '参数不正确，MOCK接口参数为[{}]'.format(route[0]['body'])})
    # 目录前只返回 json格式的数据，后期优化返回数据格式
    return HttpResponse(
        route[0]['response'],
        content_type="application/json;charset=UTF-8"
    )

    #头有缺陷，后期优化识别MOCK数据的请求头是否在request请求头里面来判断请求是否正确
    # headers_a = fac.format_headers(route[0]['headers'])
    # headers_a = demjson.decode(str(headers_a))
    # headers_a = demjson.encode(headers_a)
    # params_a = route[0]['body']
    # print(params_a)
    # print(headers_a)
    # # 如果数据库里存在这个路径
    # headers = request.headers
    #
    #
    # # 获取本次请求的请求头，不是数据库里存的请求头
    # headers = demjson.decode(str(headers))
    # headers = demjson.encode(headers)
    # print(headers)
    # # 获取本次请求的请求参数，不是数据库里存的请求参数
    # print(params)
    # params = json.dumps(params, separators=(",", ":"))


def testApi(request):
    """
    接口调试，暂不实现
    """
    if request.method == 'POST':
        try:
            pass
        except Exception as e:
            pass
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})





def getApibyId(request):
    """
    通过获取数据
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            obj_api = list(Apidata.objects.filter(Q(id=data['id'])).values())
            return JsonResponse({'code': 1, 'msg': '获取接口信息成功', 'data': obj_api})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '查询接口失败,具体原因:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})


def getApimethod(request):
    """
    获取接口类型
    """
    if request.method == 'GET':
        try:
            obj_met = list(Apimethod.objects.all().values())
            return JsonResponse({'code': 1, 'msg': '获取接口类型成功', 'data': obj_met})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '获取类型失败，具体原因:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})



def setApimock(request):
    """
    设置接口MOCK状态
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            obj_api = Apidata.objects.get(id=data['id'])
            obj_api.ismock = data['ismock']
            obj_api.save()
            return JsonResponse({'code': 1, 'msg': '修改MOCK状态成功'})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '修改MOCK状态失败，具体原因:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})

"""
接口管理相关接口------结束----------------------------------------------------------
"""






"""
用例管理相关接口------开始----------------------------------------------------------
"""
def getCasedata(request):
    """
    获取接口数据
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            res = fac.queryCase(data)
            return JsonResponse({'code': 1, 'msg': '查询数据成功:', "data": res})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '查询数据失败,具体原因:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})



def getCommonmethon(request):
    """
    公共方法类型
    """
    if request.method == 'GET':
        methodType = int(request.GET.get('menthodType'))
        try:
            obj_met = list(Commonmethod.objects.filter(Q(method_tpye=methodType)).values())
            return JsonResponse({'code': 1, 'msg': '获取接口类型成功', 'data': obj_met})
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '获取类型失败，具体原因:' + str(e)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})



def addCase(request):
    """
    新增用例
    """
    if request.method == 'POST':
        caseData = json.loads(request.body.decode('utf-8'))
        isOK, resulf = fac.addCase(caseData)
        if isOK:
            return JsonResponse({'code': 1, 'msg': resulf})
        else:
            return JsonResponse({'code': 0, 'msg': '新增用例失败，具体原因：' + str(resulf)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})



def getCaseDetail(request):
    """
    获取用例详情
    """
    if request.method == 'GET':
        caseid = int(request.GET.get('rowid'))
        isOK, result = fac.getCaseDetail(caseid)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '获取用例详情成功', 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': '获取用例详情失败,具体原因：{}'.format(str(result))})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})



def updataCaseData(request):
    """
    更新修改用例
    """
    if request.method == 'POST':
        caseData = json.loads(request.body.decode('utf-8'))
        isOK, result = fac.updataCaseData(caseData)
        if isOK:
            return JsonResponse({'code': 1, 'msg': "数据更新成功"})
        else:
            return JsonResponse({'code': 0, 'msg': '数据更新失败，具体原因{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})


def getcommethodes(request):
    """
    获取自定义方法描述
    """
    if request.method == "GET":
        isOK, result = fac.getcommethodes()
        if isOK:
            return JsonResponse({'code': 1, 'msg': '获取数据成功', 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': '获取数据失败，具体原因{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})

"""
用例管理相关接口------结束----------------------------------------------------------
"""


"""
测试计划相关接口------开始----------------------------------------------------------
"""
def addPlan(request):
    if request.method == 'POST':
        planData = json.loads(request.body.decode('utf-8'))
        isOK, result = fac.addPlan(planData)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '计划添加成功'})
        else:
            return JsonResponse({'code': 0, 'msg': "计划添加失败，具体原因{}".format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})


def getPlan(request):
    if request.method == 'GET':
        try:
            data = {}
            data['inputstr'] = request.GET.get('inputstr')
            data['pageSize'] = int(request.GET.get('pageSize'))
            data['currentPage'] = int(request.GET.get('currentPage'))
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '查询失败，具体原因{}'.format(str(e))})
        isOK, result = fac.getPlanlist(data)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '查询成功', 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': '查询失败，具体原因{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})

def getPlanDetail(request):
    if request.method == 'GET':
        planid = int(request.GET.get('rowid'))
        isOK, result = fac.getPlanDetail(planid)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '数据查询成功', 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': '数据查询失败，具体原因{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})

def updatePlan(request):
    if request.method == 'POST':
        planData = json.loads(request.body.decode('utf-8'))
        isOK, result = fac.updataPlan(planData)
        if isOK:
            return JsonResponse({'code': '1', 'msg': '更新数据成功', 'data': result})
        else:
            return JsonResponse({'code': '0', 'msg': '更新数据失败，具体原因{}'.format(result)})
    else:
        return JsonResponse({'code': '0', 'msg': '需要POST方式'})


def startorstopschedulerplan(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        isOK, result = manage.updateScheStatus(data)
        if isOK:
            isOK, result = manage.updataPlanScheStatus(data)
            if isOK:
                return JsonResponse({'code': '1', 'msg': '操作成功', 'data': result})
            else:
                if data['scheStatus'] == 0:
                    data['scheStatus'] == 1
                else:
                    data['scheStatus'] == 0
                manage.updataPlanScheStatus(data)
                return JsonResponse({'code': '0', 'msg': '操作失败{}'.format(result)})
        else:
            return JsonResponse({'code': '0', 'msg': '操作失败{}'.format(result)})
    else:
        return JsonResponse({'code': '0', 'msg': '需要POST方式'})

"""
测试计划相关接口------结束----------------------------------------------------------
"""



"""
测试执行相关接口------开始----------------------------------------------------------
"""
def caseExceute(request):
    if request.method == 'POST':
        try:
            caseid = json.loads(request.body.decode('utf-8'))['caseid']
            envid = json.loads(request.body.decode('utf-8'))['envid']
            run = Runingfac(exetype=0, id=caseid, env_id=envid)
            run.start()
            return JsonResponse({'code': '1', 'msg': "触发用例执行成功"})
        except Exception as e:
            return JsonResponse({'code': '0', 'msg': '触发用例执行失败，具体原因[{}]'.format(str(e))})
    else:
        return JsonResponse({'code': '0', 'msg': '需要POST方式'})


def planExcute(request):
    if request.method == 'POST':
        try:
            planid = json.loads(request.body.decode('utf-8'))['planid']
            run = Runingfac(exetype=1, id=planid)
            run.start()
            return JsonResponse({'code': '1', 'msg': "触发计划执行成功"})
        except Exception as e:
            return JsonResponse({'code': '0', 'msg': '触发计划执行失败，具体原因[{}]'.format(str(e))})
    else:
        return JsonResponse({'code': '0', 'msg': '需要POST方式'})


"""
测试执行相关接口------结束----------------------------------------------------------
"""




"""
测试报告相关接口------开始----------------------------------------------------------
"""

def getCaseReports(request):
    if request.method == 'GET':
        planid = int(request.GET.get('rowid'))
        isOK, result = fac.getCaseRoprts(planid)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '测试报告获取成功', 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': '测试报告获取失败，具体原因{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})


def getRoportDetail(request):
    if request.method == 'GET':
        planid = int(request.GET.get('rowid'))
        isOK, result = fac.getReportDatail(planid)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '测试报告获取成功', 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': '测试报告获取失败，具体原因{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})


def getPlanExRecord(request):
    if request.method == 'GET':
        planid = int(request.GET.get('planid'))
        isOK, result = fac.getPlanExRecord(planid)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '获取执行记录成功', 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': '获取执行记录成功，具体原因{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})

def getRecortCaseRep(request):
    if request.method == 'GET':
        planid = int(request.GET.get('planid'))
        excutnum = int(request.GET.get('excutnum'))
        isOK, result = fac.getRecortCaseRep(planid, excutnum)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '获取执行记录成功', 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': '获取执行记录成功，具体原因{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})

"""
测试报告相关接口------结束----------------------------------------------------------
"""


"""
Swagger抓取接口------开始----------------------------------------------------------
"""
def getSwaggerIntoData(request):
    if request.method == 'POST':
        url = json.loads(request.body.decode('utf-8'))['url']
        name = json.loads(request.body.decode('utf-8'))['name']
        isOK, result = manage.getSwaggerIntoDatabase(url, name)
        if isOK:
            return JsonResponse({'code': 1, 'msg': 'Swagger数据更新成功', 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': 'Swagger数据更新失败，具体原因{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})


"""
Swagger抓取接口------结束----------------------------------------------------------
"""


"""
定时任务------开始----------------------------------------------------------
"""
def add_job(request):
    if request.method == 'POST':
        id = json.loads(request.body.decode('utf-8'))['id']
        isOK, result = manage.add_job(id)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '定时任务启动成功', 'data': result})
        else:
            return JsonResponse({'code':0, 'msg': '定时任务启动失败，具体原因{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})


def romove_job(request):
    if request.method == 'POST':
        id = json.loads(request.body.decode('utf-8'))['id']
        isOK, result = manage.romove_job(id)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '定时任务停止成功', 'data': result})
        else:
            return JsonResponse({'code':0, 'msg': '定时任务停止失败，具体原因{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})

"""
定时任务------结束----------------------------------------------------------
"""

"""
导入用例------开始----------------------------------------------------------
"""


def importCsae(request):
    if request.method == 'POST':
        try:
            file_obj = request.FILES.get('file')  # 获取到文件对象
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '用例导入失败，具体原因：{}'.format(str(e))})
        isOK, result = manage.importCsae(file_obj)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '用例导入成功', 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': '用例导入失败，具体原因：{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要POST方式'})


def getImportRecord(request):
    if request.method == 'GET':
        isOK, result = manage.getImportRecord()
        if isOK:
            return JsonResponse({'code': 1, 'msg': '用例记录获取成功', 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': '用例记录获取失败，具体原因：{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})

from django.utils.encoding import escape_uri_path

def getImportFile(request):
    if request.method == 'GET':
        try:
            filename = str(request.GET.get('filename'))
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '用例记录文件下载失败，具体原因：{}'.format(str(e))})
        isOK, result = manage.getImportFile(filename)
        if isOK:
            response = StreamingHttpResponse(result)
            # 增加headers
            response['Content-Type'] = 'application/octet-stream'
            response['Access-Control-Expose-Headers'] = "Content-Disposition, Content-Type"
            response['Content-Disposition'] = "attachment; filename={}".format(escape_uri_path(filename))
            return response
        else:
            return JsonResponse({'code': 0, 'msg': '用例记录文件下载失败，具体原因：{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})

def getCaseModel(request):
    """
    获取用例模板
    """
    if request.method == 'GET':
        isOK, result = manage.getCaseModel()
        if isOK:
            response = StreamingHttpResponse(result)
            # 增加headers
            response['Content-Type'] = 'application/octet-stream'
            response['Access-Control-Expose-Headers'] = "Content-Disposition, Content-Type"
            response['Content-Disposition'] = "attachment; filename={}".format(escape_uri_path("用例模板.xlsx"))
            return response
        else:
            return JsonResponse({'code': 0, 'msg': '用例模板下载失败，具体原因：{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})


def getHelpFile(request):
    """
    获取帮助文档
    """
    if request.method == 'GET':
        isOK, result = manage.getHelpFile()
        if isOK:
            response = StreamingHttpResponse(result)
            # 增加headers
            response['Content-Type'] = 'application/octet-stream'
            response['Access-Control-Expose-Headers'] = "Content-Disposition, Content-Type"
            response['Content-Disposition'] = "attachment; filename={}".format(escape_uri_path("接口自动化平台使用手册.docx"))
            return response
        else:
            return JsonResponse({'code': 0, 'msg': '用例模板下载失败，具体原因：{}'.format(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})


"""
执行记录------结束----------------------------------------------------------
"""

def getExeRecord(request):
    if request.method == 'GET':
        try:
            data = {}
            data['inputstr'] = request.GET.get('inputstr')
            data['pageSize'] = int(request.GET.get('pageSize'))
            data['currentPage'] = int(request.GET.get('currentPage'))
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '获取执行记录失败，具体错误' + str(e)})
        isOK, result = manage.getExeRecord(data)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '获取执行记录成功', 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': '获取执行记录失败，具体错误' + str(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})

def getRecortCaseRepByNum(request):
    if request.method == 'GET':
        try:
            data = {}
            data['pageSize'] = int(request.GET.get('pageSize'))
            data['currentPage'] = int(request.GET.get('currentPage'))
            data['excutnum'] = str(request.GET.get('excutnum'))
            data['status'] = int(request.GET.get('status'))
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '获取用例报告列表失败，具体错误' + str(e)})
        isOK, result = manage.getRecortCaseRepByNum(data)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '获取用例报告列表成功', 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': '获取用例报告列表失败，具体错误' + str(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})

def getRecordInfo(request):
    """
    获取测试报告信息
    """
    if request.method == 'GET':
        try:
            excutnum = int(request.GET.get('excutnum'))
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': '获取用例报告列表失败，具体错误' + str(e)})
        isOK, result = manage.getRecordInfo(excutnum)
        if isOK:
            return JsonResponse({'code': 1, 'msg': '获取用例报告列表成功', 'data': result})
        else:
            return JsonResponse({'code': 0, 'msg': '获取用例报告列表失败，具体错误' + str(result)})
    else:
        return JsonResponse({'code': 0, 'msg': '需要GET方式'})

"""
执行记录------结束----------------------------------------------------------
"""
